import * as vscode from "vscode";
import { ExtensionContext } from "vscode";
import { ConfigurationEnum, configurationUtil } from "./ConfigurationUtil";
import * as path from "path";
import { pathUtil } from "./PathUtil";
import { start } from "../start";

/**
 * 检查当前是否打开的工作目录
 */
export const checkWorkFolder = (workPath = configurationUtil.get(ConfigurationEnum.workPath)): boolean => {
    let result = false;
    for (const folder of vscode.workspace.workspaceFolders ?? []) {
        if (folder.uri.fsPath === workPath) {
            result = true;
            break;
        }
    }
    return result;
};


/**
 * 打开工作目录
 */
export const openWorkFolder = (context: ExtensionContext, workPath = configurationUtil.get(ConfigurationEnum.workPath)) => {
    if (workPath) {
        if (checkWorkFolder(workPath)) {
            start(context);
        } else {
            const uri = vscode.Uri.file(workPath);
            vscode.commands.executeCommand("vscode.openFolder",
                uri,
                {
                    forceNewWindow: false,
                    noRecentEntry: true
                }
            );
        }
    } else {
        selectWorkFolder(context);
    }
};

/**
 * 选择工作目录
 */
export const selectWorkFolder = (context: ExtensionContext) => {
    let uri = vscode.Uri.file(path.join(pathUtil.home));
    vscode.window.showOpenDialog({
        canSelectFiles: false,
        canSelectFolders: true,
        canSelectMany: false,
        defaultUri: uri,
        openLabel: "选择",
        title: "选择 LeetCode Ultimate 插件工作目录"
    }).then(res => {
        if (res) {
            configurationUtil.update(ConfigurationEnum.workPath, res[0].fsPath).then(() => {
                openWorkFolder(context, res[0].fsPath);
            });
        } else {
            vscode.window.showWarningMessage("需要选择工作目录才能继续", "选择").then(res => {
                if (res) {
                    selectWorkFolder(context);
                }
            });
        }
    });
};